package com.education.common.utils;

import com.education.common.config.BusinessException;
import com.education.common.config.CommonErrorCode;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;


public class QiniuUtil {

    private static final Logger logger = Logger.getLogger(QiniuUtil.class);

    //设置好账号的ACCESS_KEY和SECRET_KEY
    static final String ACCESS_KEY = "TWDj6oF-ZkhXLmn8Iipc0woi6teoq-jerUpwuW3s";
    static final String SECRET_KEY = "S6FGTu-FfkSIoii0k9jUwRz2S5Xlac7VhVl_cELy";
    //要上传的空间
    static final String BUCKET_NAME = "jinruanresource";
    static final String QINIU_DOMAIN = "http://jinruanresource.shixuncloud.com/";
    /**
     * 七牛桶目录
     */
    private static final String QINIU_FILE_DIRECTORY = "informatization4.0/";


    /**
     * 七牛云上传图片   文件流  inputstream
     *
     * @param inputStream
     * @return
     */
    public static String uoloapQiniuStream(InputStream inputStream, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;//指定分片上传版本
        cfg.resumableUploadMaxConcurrentTaskCount = 10;  // 设置分片上传并发，1：采用同步上传；大于1：采用并发上传

        //构造器分片
        UploadManager uploadManager1 = new UploadManager(cfg, null);

        //其他参数参考类注释
        //UploadManager uploadManager = new UploadManager(cfg);
        //String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //String key = System.currentTimeMillis()+"."+suffix;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME);
        String result = null;
        try {
            //a.文件路径上传
            //Response response = uploadManager.put(localFilePath, key, upToken);
            //b.数据流上传
            //Response response = uploadManager.put(inputStream, fileName, upToken, null, null);//目前
            Response response = uploadManager1.put(inputStream, 62263995, fileName, upToken, null, null, false);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            result = fileName;
        } catch (QiniuException ex) {
            result = "文件上传失败";
        }
        return result;
    }

    /**
     * 七牛云上传图片
     *
     * @param localFilePath
     * @return
     */
    public String uoloapQiniu(File localFilePath, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = ACCESS_KEY;
        String secretKey = SECRET_KEY;
        String bucket = BUCKET_NAME;
        //如果是Windows情况下，格式是 D:\23912475_130759767000_2.jpg
        //String localFilePath = "D:\\23912475_130759767000_2.jpg";
        //        String localFilePath = "/home/qiniu/test.png";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //  String key = "images/"+fileName+"?tId="+System.currentTimeMillis();
        String key = QINIU_FILE_DIRECTORY + System.currentTimeMillis() + "." + suffix;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        String result = null;

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            logger.info("{七牛图片上传key: " + putRet.key + ",七牛图片上传hash: " + putRet.hash + "}");

            result = key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            result = null;
        }
        return result;
    }

    //删除文件
    public static void deleteFileFromQiniu(String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        String key = fileName;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            if (key.contains("1670306092028.png") ||
                    key.contains("1670306015230.png") ||
                    key.contains("4.0defaultavatar.png")) {
                return;
            }
            Response delete = bucketManager.delete(BUCKET_NAME, key);
            logger.info(delete);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            ex.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_200104);
        }
    }

    //批量删除
    public static void deleteFileFromQinius(List<String> fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            for (String key : fileName) {
                if (key.contains("1670306092028.png") ||
                        key.contains("1670306015230.png") ||
                        key.contains("4.0defaultavatar.png")) {
                } else {
                    bucketManager.delete(BUCKET_NAME, key);
                }
            }
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            ex.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_200104);
        }
    }

    /**
     * 七牛云上传token
     *
     * @return
     */
    public static String createToken() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME, null, 3600, null);
        return upToken;
    }

    public static Configuration cfg = new Configuration(Region.region0());

    /**
     * 获取文件信息
     */
    public static boolean estimateIsExist(String key) {
        try {
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            BucketManager bucket = new BucketManager(auth, cfg);
            FileInfo stat = bucket.stat(BUCKET_NAME, key);
            //System.out.println(stat);
            return true;
        } catch (QiniuException e) {
//           e.printStackTrace();
            return false;
        }
    }

    /**
     * 生成文件名称
     *
     * @return
     */
    public static String getFileName(MultipartFile file) {
        String suffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        String time = DateUtils.dateTimeNow();
        StringBuilder builder = new StringBuilder();
        return builder.append(time).append(UUIDUtils.getByUUId()).append(".").append(suffix).toString();
    }

    /**
     * 上传文件字节码无返回值
     *
     * @param bytes
     * @param fileName
     */
    public static void upload2Qiniu(byte[] bytes, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME);
        try {
            Response response = uploadManager.put(bytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 上传文件字节码有返回值
     *
     * @param bytes
     * @param fileName
     */
    public static String upload2QiniuAndString(byte[] bytes, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME);
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String key = QINIU_FILE_DIRECTORY + System.currentTimeMillis() + "." + suffix;
        String result;
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            logger.info("{七牛图片上传key: " + putRet.key + ",七牛图片上传hash: " + putRet.hash + "}");

            result = key;
        } catch (QiniuException ex) {
            ex.printStackTrace();
            result = "";
        }
        return result;
    }

    public static void downLoadFile(String fileUrl, HttpServletResponse response) throws IOException {
        //1.获取要下载的文件的绝对路径
        //2.获取要下载的文件名
        URL url = new URL("http://jinruanresource.shixuncloud.com/" + fileUrl);
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileUrl, "UTF-8"));
        //4.获取要下载的文件输入流
        //2.获取链接
        URLConnection conn = url.openConnection();
        //3.输入流
        InputStream inStream = conn.getInputStream();
        int len = 0;
        //5.创建数据缓冲区
        byte[] buffer = new byte[1024];
        //MagicMatch match = Magic.getMagicMatch(buffer);
        //String mimeType = match.getMimeType();
        response.setContentType("application/msword");
        //6.通过response对象获取OutputStream流
        OutputStream out = response.getOutputStream();
        //7.将FileInputStream流写入到buffer缓冲区
        while ((len = inStream.read(buffer)) > 0) {
            //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
            out.write(buffer, 0, len);
        }
//        return out;
        inStream.close();
    }

}
